# base class for column objects
class Present::Column
  include Present::Configurable
  def initialize(name, options = {})
    options[:name] = name
    super(options)
  end

  # the name of the column
  attr_accessor :name

  # the label of the column
  attr_accessor :label
  def label
    @label ||= name.to_s.titleize
  end

  # how to get the column's value from a record
  attr_accessor :value
  def value_for(view = nil, record = nil)
    case value
      # just return the string ... it's constant
      when String
      value

      # call the custom column renderer
      when Proc
      value.call(record)

      # call the specified method on record
      when Symbol
      record.send(value)

      when Present::UIObject
      value.view = view
      value.render(record)

      else
      raise NotImplementedError
    end
  end

  def self.collection_from_hash(hash)
    hash.inject([]) do |columns, (k, v)|
      if v.is_a? Hash
        c = new(k, v)
      else
        c = new(k)
        c.value = v
      end
      columns << c
    end
  end

  def self.collection_from_array(array)
    array.inject([]) do |columns, v|
      if v.is_a? self
        c = v
      elsif v.is_a? Hash
        c = new(v[:name], v)
      else
        c = new(v)
        c.value = v.to_sym
      end
      columns << c
    end
  end
end